package com.tianji.promotion.task;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.utils.CollUtils;
import com.tianji.promotion.domain.enums.CouponStatus;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.service.ICouponService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class PromotionTask {
    private final ICouponService couponService;

    @XxlJob("couponIssueJobHandler")
    public void couponIssueJobHandler() throws Exception {
        log.info("优惠券发放与结束时间检测中");
        int index = XxlJobHelper.getShardIndex();  //0，1
        int total = XxlJobHelper.getShardTotal(); //例如:2
        int pageNo = index + 1; // 起始页，就是分片序号+1
        Page<Coupon> page = new Page<>();
        page.setSize(100);
        //分页查询并修改
        while (true) {

            //1.获取所有状态为待发放或进行中的优惠券优惠券
            LocalDateTime now = LocalDateTime.now();

            IPage<Coupon> page1 = couponService.lambdaQuery()
                    .or(i -> i.eq(Coupon::getStatus, CouponStatus.DRAFT).le(Coupon::getIssueBeginTime, now))
                    .or(i -> i.eq(Coupon::getStatus, CouponStatus.ISSUING).le(Coupon::getIssueEndTime, now))
                    .orderByDesc(Coupon::getCreateTime)
                    .page(page.setPages(pageNo));
            List<Coupon> records = page1.getRecords();
            if(CollUtils.isEmpty(records)){
                break;
            }

            //开始修改状态
            List<Coupon> collect = records.stream().map(coupon ->
                    coupon.setStatus(coupon.getStatus().equals(CouponStatus.DRAFT) ? CouponStatus.ISSUING : CouponStatus.FINISHED)
            ).collect(Collectors.toList());

            //批量修改
            couponService.updateBatchById(collect);

            //翻页
            pageNo+= total;

        }

    }


}
